package com.a01_2021.thousandstimes.instance.controller;


import com.a01_2021.thousandstimes.exception.CustomException;
import com.a01_2021.thousandstimes.general.jwt.JwtTokenUtil;
import com.a01_2021.thousandstimes.instance.entity.Communication;
import com.a01_2021.thousandstimes.instance.service.ICommunicationService;
import com.a01_2021.thousandstimes.utils.AjaxResponse;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author E1xP
 * @since 2021-03-30
 */
@RestController
@RequestMapping("/communication")
public class CommunicationController {

    @Resource
    JwtTokenUtil jwtTokenUtil;

    @Resource
    ICommunicationService communicationService;

    /**
     * 用于发送沟通消息
     *
     * @param token        jwt令牌
     * @param targetUserId 消息目标用户id
     * @param content      发送内容
     * @return AjaxResponse
     * @throws CustomException 但目标用户不存在时抛出该异常
     */
    @PreAuthorize("hasAuthority('communication-send')")
    @DS("#header.instanceid")
    @PostMapping("send")
    public AjaxResponse send(@RequestHeader("${jwt.header}") String token, long targetUserId, String content) throws CustomException {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        Communication communication = communicationService.send(userId, targetUserId, content);
        return AjaxResponse.success(communication);
    }

    /**
     * 用于获取特定时间之后某用户收到的消息
     *
     * @param token jwt令牌
     * @param time  特定时间
     * @return AjaxResponse
     */
    @PreAuthorize("hasAuthority('communication-receive')")
    @DS("#header.instanceid")
    @PostMapping("receive")
    public AjaxResponse receive(@RequestHeader("${jwt.header}") String token, LocalDateTime time) {
        long userId = Long.parseLong(jwtTokenUtil.getUserIdFromToken(token));
        List<Communication> communicationList = communicationService.receive(userId, time);
        return AjaxResponse.success(communicationList);
    }
}
